package com.mobileservice.autoreply.ui.customizeui;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;

import com.mobileservice.autoreply.R;
import com.mobileservice.autoreply.activity.AutoReplyActivity;
import com.mobileservice.autoreply.data.manager.PhoneContactManager;
import com.mobileservice.autoreply.ui.model.PhoneContactModel;

public class CustomSmSTemplateDialog extends Dialog implements android.view.View.OnClickListener {

	private View tabtop, tabbody;
	private ImageButton close_dialog, okey_dialog_btn;
	private EditText inputMessage;
	private Context mContext;
	private PhoneContactModel PhoneModel;

	public CustomSmSTemplateDialog(Context context, PhoneContactModel model) {
		super(context, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);

		setContentView(R.layout.setting_dialog_layout);
		tabtop = findViewById(R.id.toptab);
		tabbody = findViewById(R.id.body_tab);
		close_dialog = (ImageButton) tabtop.findViewById(R.id.closeDialog);
		okey_dialog_btn = (ImageButton) tabtop.findViewById(R.id.okey_dialog);
		inputMessage = (EditText) tabbody.findViewById(R.id.editorSms);
		mContext = context;
		this.PhoneModel = model;
		/** Auto Reply Message */
		inputMessage.setText(model.getAutoReplyMessage());
		/** Setup Button Listener */
		close_dialog.setOnClickListener(this);
		okey_dialog_btn.setOnClickListener(this);

	}

	private class LoadSmsTemplateTask extends AsyncTask<Void, Void, Void> {

		protected ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressDialog = ProgressDialog.show(mContext, "", "");
		}

		@Override
		protected Void doInBackground(Void... params) {
			PhoneContactManager contactManager = PhoneContactManager.getInstance(mContext);
			PhoneModel.setAutoReplyMessage(inputMessage.getText().toString());
			contactManager.UpdatePhoneContacts(PhoneModel);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (!((Activity) mContext).isFinishing() || progressDialog.isShowing()) {
				progressDialog.cancel();
				progressDialog = null;
			}
			CustomSmSTemplateDialog.this.cancel();

			if (mContext instanceof AutoReplyActivity) {
				((AutoReplyActivity) mContext).Refresh();
			}
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.closeDialog:
			cancel();
			break;

		case R.id.okey_dialog:
			new LoadSmsTemplateTask().execute();
			break;

		}

	}

}
